package com.sample.rx3.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

public abstract class BasicFragment extends Fragment {

    private IFrag2ActImpl mListener;

    public @LayoutRes
    int fragLayoutRes() {
        return 0;
    }

    public abstract void afterOnCreate();

    /**
     * mBinding =  DataBindingUtil.inflate(inflater, fragLayoutRes(),container,false);
     * View view = mBinding.getRoot();
     * initView(view);
     * return view;
     */
    @Nullable
    public View inflaterView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(fragLayoutRes(), container, false);
    }

    public void unbind() {
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof IFrag2ActImpl) {
            mListener = (IFrag2ActImpl) context;
        } else {
            throw new RuntimeException(context
                    + " must implement IFrag2ActListener");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflaterView(inflater, container);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        afterOnCreate();
    }

    public void onFrag2Act(String tag,@Nullable Object objTag) {
        if (null != mListener) {
            mListener.onFrag2Act(tag, objTag);
        }
    }

    public @Nullable Intent getIntent() {
        FragmentActivity activity = getActivity();
        if (null != activity)
            return activity.getIntent();
        return null;
    }

    public void finish() {
        FragmentActivity activity = getActivity();
        if (null != activity)
            activity.finish();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbind();
    }
}
